package com.dt.common.validation.definition;

import java.math.BigDecimal;
import java.math.BigInteger;
import java.util.Map;

import com.dt.common.validation.annotation.Min;
import com.dt.common.validation.impl.DefaultValidationDefinition;
import com.dt.common.validation.itf.ConstraintValidation;
import com.dt.common.validation.itf.ValidationContext;

import lombok.Setter;

@Setter
public class MinDefinition extends DefaultValidationDefinition {
	private long minValue;

	public MinDefinition() {
		this.name = Min.class.getSimpleName();
	}

	@Override
	protected void fillMsgInterpolatingParams(Map<String, String> params) {
		params.put("value", Long.valueOf(minValue).toString());
	}

	@Override
	public ConstraintValidation buildValidation() {

		return new ConstraintValidation() {

			@Override
			public boolean isValid(ValidationContext context, Object objectValue, Object propertyValue) {
				if (propertyValue == null) {
					return true;
				}
				if (propertyValue instanceof Number) {
					Number number = (Number) propertyValue;
					if (propertyValue instanceof BigDecimal) {
						return ((BigDecimal) number).compareTo(BigDecimal.valueOf(minValue)) >= 0;
					} else if (propertyValue instanceof BigInteger) {
						return ((BigInteger) number).compareTo(BigInteger.valueOf(minValue)) >= 0;
					} else {
						return number.longValue() >= minValue;
					}
				} else if (propertyValue instanceof String) {
					try {
						return new BigDecimal((String) propertyValue).compareTo(BigDecimal.valueOf(minValue)) >= 0;

					} catch (NumberFormatException e) {
						return false;
					}
				}

				return false;
			}

		};

	}

}
